package com.top.mall.main.cart

import android.view.View
import android.widget.CheckBox
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.*
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeFragment
import com.top.mall.R
import com.top.mall.app.BaseApplication
import com.top.mall.custom.setTransitionStatus
import com.top.mall.dialog.LoadingDialog
import com.top.mall.entity.*
import com.top.mall.jetpack.vm.CartViewModel
import com.top.mall.main.goods.adapter.GoodsCartAdapter
import com.top.mall.main.goods.GoodsDetailsActivity
import com.top.mall.main.mine.MineShopActivity
import com.top.mall.main.order.OrderSettlementActivity
import kotlinx.android.synthetic.main.fragment_main_cart.*
import java.text.DecimalFormat

class CartFragment : OwnerViewModeFragment<CartViewModel>() {

    companion object {
        fun newInstance(): CartFragment {
            return CartFragment()
        }
    }

    private val goodsCartAdapter: GoodsCartAdapter = GoodsCartAdapter()

    override val layoutResId: Int
        get() = R.layout.fragment_main_cart

    override fun viewModel(): CartViewModel {
        return createViewModel()
    }

    override fun stateBar(): StatusBar {
        return StatusBar(view = clCartBar)
    }

    override fun initView() {
        //为Toolbar添加状态栏高度
        BarUtils.addMarginTopEqualStatusBarHeight(clCartBar)

        rvCartGoodsBody.apply {
//            itemAnimator?.changeDuration = 0
        }.adapter = goodsCartAdapter

        goodsCartAdapter.setOnItemClickListener { _, view, position ->
            val itemData = goodsCartAdapter.getItem(position)
            GoodsDetailsActivity.open(itemData.goods_id)
        }

        goodsCartAdapter.setOnItemChildClickListener { _, view, position ->
            val itemData: CartList = goodsCartAdapter.getItem(position)
            when (view.id) {
                R.id.cbGoodsCartOpt -> {
                    viewModel.updateCartListLiveData(
                        CartType.UPDATE,
                        itemData.cart_id,
                        isSelected = (view as CheckBox).isChecked
                    )
                }
                R.id.ivGoodsCartDelete -> this.showDialogDelete(
                    message = "是否从购物车删除？",
                    cartIds = arrayOf(itemData.cart_id),
                    type = CartType.DELETE
                )
                R.id.flGoodsCartPlus -> viewModel.cartChangeNum(
                    itemData.cart_id, (itemData.goods_num + 1), position
                )
                R.id.flGoodsCartReduce -> (itemData.goods_num - 1).let {
                    if (it == 0) {
                        this.showDialogDelete(
                            message = "是否从购物车删除？",
                            cartIds = arrayOf(itemData.cart_id),
                            type = CartType.DELETE
                        )
                        return@setOnItemChildClickListener
                    }
                    viewModel.cartChangeNum(itemData.cart_id, it, position)
                }
            }
        }

        //位置地址
        tvCartGoodsLocal.setOnClickListener {
            MineShopActivity.open(requireActivity())
        }

        //领券
        tvCartGoodsClear.setOnClickListener {

        }

        //清空购物车
        tvCartGoodsClear.setOnClickListener {
            val cartIds: Array<Int> =
                goodsCartAdapter.data.map { it.cart_id }.toTypedArray()
            this.showDialogDelete(
                message = "您确定要清空购物车吗？",
                cartIds = cartIds,
                type = CartType.CLEAR
            )
        }

        //全选
        cbCartGoodsAll.setOnClickListener {
            viewModel.updateCartListLiveData(
                CartType.SELECTED, isSelected = cbCartGoodsAll.isChecked
            )
        }

        //去结算
        tvCartGoodsSettle.setOnClickListener {
            val cartIds: Array<Int> =
                goodsCartAdapter.data.filter { it.isSelected }.map { it.cart_id }.toTypedArray()
            if (cartIds.isNullOrEmpty()) {
                toast("请选择物品")
                return@setOnClickListener
            }
            viewModel.cartSettlement(cartIds)
        }
    }

    override fun initData() {
        if (BaseApplication.getCartListLiveData().value == null) {
            viewModel.cartIndex()
        }
    }

    override fun initViewMode() {
        viewModel.cartListLiveData.observe(this, Observer { response ->
            when (response.status) {
                Status.START -> {
                    goodsCartAdapter.setEmptyView(createLoadingView())
                }
                Status.SUCCESS -> {
                    goodsCartAdapter.removeEmptyView()
                }
                Status.FAILURE -> {
                    goodsCartAdapter.removeEmptyView()
                    toast(response.error?.msg)
                }
            }
        })

        viewModel.cartChangeNumLiveData.observe(viewLifecycleOwner, Observer { response ->

            when (response.status) {
                Status.START -> {

                }
                Status.SUCCESS -> {

                }
                Status.FAILURE -> {
                    toast(response.error?.msg)
                }
            }
        })

        viewModel.cartDeleteLiveData.observe(viewLifecycleOwner, Observer { response ->
            when (response.status) {
                Status.START -> {
                    LoadingDialog.show(requireContext())
                }
                Status.SUCCESS -> response.data?.let { httpData ->
                    LoadingDialog.dismiss()
                }
                Status.FAILURE -> {
                    toast(response.error?.msg)
                    LoadingDialog.dismiss()
                }
            }
        })

        viewModel.settlementCartLiveData.observe(viewLifecycleOwner, { response ->
            this.setTransitionStatus(response)
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data ?: return@observe
            OrderSettlementActivity.open(data)
        })

        BaseApplication.getCartListLiveData().observe(viewLifecycleOwner, Observer { cartLis ->
            fillDataVisibility(cartLis)
        })

    }

    private fun fillDataVisibility(cartList: MutableList<CartList>) {

        val isSizeZero: Boolean = cartList.size != 0
        val isReducePrice: Boolean = !cartList.none { item ->
            !item.reduce_price.isNullOrEmpty()
        }
        tvCardGoodsHint.visibility =
            if (isReducePrice) View.VISIBLE else View.GONE
        clCartGoodsBottom.visibility =
            if (isSizeZero) View.VISIBLE else View.GONE
        tvCartGoodsClear.visibility =
            if (isSizeZero) View.VISIBLE else View.GONE

        goodsCartAdapter.setList(cartList)
        if (!isSizeZero) {
            goodsCartAdapter.setEmptyView(createNullDataView())
        }

        fillDataUndulate(cartList.filter { it.isSelected }.toMutableList())
    }

    private fun fillDataUndulate(selectedCartList: MutableList<CartList>) {
        val selectedSize: Int = selectedCartList.size

        cbCartGoodsAll.isChecked =
            selectedSize == goodsCartAdapter.data.size && selectedSize != 0
        tvCartGoodsPrice.visibility = if (selectedSize == 0)
            View.GONE else View.VISIBLE

        var num: Int = 0
        var price: Double = 0.00
        selectedCartList.forEach {
            num += it.goods_num
            price += it.goods_num * if (it.active_price == "0")
                it.goods_price.toDouble()
            else it.active_price.toDouble()
        }

        cbCartGoodsAll.text =
            if (selectedSize == 0) "全选" else "已选($num)"
        tvCartGoodsPrice.text = StringBuilder("￥")
            .append(DecimalFormat(("############0.00")).format(price))
    }

    private fun showDialogDelete(message: String, cartIds: Array<Int>, type: CartType) {
        AlertDialog.Builder(requireContext()).setMessage(message)
            .setPositiveButton("确定") { dialog, _ ->
                viewModel.cartDelete(cartIds, type)
                dialog.cancel()
            }.setNegativeButton("取消", null)
            .show()
    }


    private fun createLoadingView(): View {
        return layoutInflater.inflate(R.layout.dialog_load_style_2, null)
    }

    private fun createNullDataView(): View {
        return layoutInflater.inflate(R.layout.view_empty_null, null)
    }

//    /**
//     * 购物车头部
//     * */
//    private fun createHeader(): View = TextView(requireContext()).apply {
//        text = "现在下单，明天最早几点送达"
//        setBackgroundResource(R.drawable.bg_radius_20dp_fbe)
//        setTextColor(resources.getColor(R.color.FF_333333))
//        textSize = 12f
//        gravity = Gravity.CENTER
//        layoutParams = LinearLayout.LayoutParams(
//            LinearLayout.LayoutParams.MATCH_PARENT,
//            ConvertUtils.dp2px(30f)
//        ).apply {
//            setMargins(
//                ConvertUtils.dp2px(13f),
//                ConvertUtils.dp2px(10f),
//                ConvertUtils.dp2px(13f),
//                ConvertUtils.dp2px(5f)
//            )
//        }
//    }
}